package com.baitengsoft.patentapimonitor.api.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baitengsoft.patentapimonitor.api.dao.AdminDataauditDao;
import com.baitengsoft.patentapimonitor.api.dao.ScheduleJobDao;
import com.baitengsoft.patentapimonitor.api.dao.WebPlatFormAreaDao;
import com.baitengsoft.patentapimonitor.api.dao.WebPlatformDao;
import com.baitengsoft.patentapimonitor.api.entity.*;
import com.baitengsoft.patentapimonitor.api.model.PlatformResult;
import com.baitengsoft.patentapimonitor.api.model.WebPlatformViewModel;
import com.baitengsoft.patentapimonitor.api.model.param.EditPlatformParam;
import com.baitengsoft.patentapimonitor.api.model.param.PlatformParam;
import com.baitengsoft.patentapimonitor.api.model.param.PlatformViewParam;
import com.baitengsoft.patentapimonitor.api.service.*;
import com.baitengsoft.patentapimonitor.common.utils.PageResult;
import com.baitengsoft.patentapimonitor.common.utils.Res;
import com.baitengsoft.patentapimonitor.common.utils.SysParamaterUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * @author Chen 2017/12/20
 */
@Service
public class WebPlatformServiceImpl extends BaseServiceImpl<WebPlatformEntity> implements WebPlatformService {

    @Autowired
    org.dozer.Mapper mapper;
    @Autowired
    private WebPlatformDao webPlatformDaoDao;
    @Autowired
    private WebRolesService webRolesService;
    @Autowired
    private CfgAreaService cfgAreaService;
    @Autowired
    private WebPlatformareaService web_platformareaService;
    @Autowired
    private WebPlatFormAreaDao webPlatFormAreaDao;
    @Autowired
    private ScheduleJobService scheduleJobService;
    @Autowired
    private AdminDataauditService adminDataauditService;
    @Autowired
    private AdminDataauditDao adminDataauditDao;
    @Autowired
    private ScheduleJobDao scheduleJobDao;
    @Autowired
    private CfgPatentIndicatorService cfgPatentIndicatorService;

    @Autowired
    private SysParamaterUtil sysParamaterUtil;


    private static final Integer[] rightYearFeeExpiredMonths = {1, 2, 3};
    private static final Integer[] rightExpiredMonths = {1, 3, 6, 12, 24};
    //四个直辖市
    private static final String[] UNIQUE_CITY = {"北京", "上海", "天津", "重庆"};

    /**
     * 根据平台id修改平台时间范围
     */
    @Override
    public Res updateTimeRanges(EditPlatformParam editPlatformParam) {

        if (!Arrays.asList(rightYearFeeExpiredMonths).contains(editPlatformParam.getYearFeeExpiredMonths())) {
            return Res.error("请求参数有误");
        }

        if (!Arrays.asList(rightExpiredMonths).contains(editPlatformParam.getExpiredMonths())) {
            return Res.error("请求参数有误");
        }
        WebPlatformEntity webPlatformEntity = webPlatformDaoDao.selectByPrimaryKey(editPlatformParam.getPlatformid());
        if (webPlatformEntity == null) {
            return Res.error("获取平台信息失败，请联系管理员！");
        }
        webPlatformEntity.setYearfeeexpiredmonths(editPlatformParam.getYearFeeExpiredMonths());
        webPlatformEntity.setExpiredmonths(editPlatformParam.getExpiredMonths());
        int i = webPlatformDaoDao.updateByPrimaryKey(webPlatformEntity);
        if (i > 0) {
            return Res.ok("更新成功！");
        }
        return Res.error("更新失败！");
    }

    /**
     * 根据平台id修改数据源属性
     */
    @Override
    public Res updateDataSource(EditPlatformParam editPlatformParam) {
        if (!(editPlatformParam.getHomepageapplydate() == 1 || editPlatformParam.getHomepageapplydate() == 2)) {
            return Res.error("请求参数有误");
        }
        if (!(editPlatformParam.getNormzlsq() == 1 || editPlatformParam.getNormzlsq() == 2)) {
            return Res.error("请求参数有误");
        }
        if (!(editPlatformParam.getNormzlsqfm() == 1 || editPlatformParam.getNormzlsqfm() == 2)) {
            return Res.error("请求参数有误");
        }
        WebPlatformEntity webPlatformEntity = webPlatformDaoDao.selectByPrimaryKey(editPlatformParam.getPlatformid());
        if (webPlatformEntity == null) {
            return Res.error("获取平台信息失败，请联系管理员！");
        }
        webPlatformEntity.setHomepageapplydate(editPlatformParam.getHomepageapplydate());
        webPlatformEntity.setNormzlsq(editPlatformParam.getNormzlsq());
        webPlatformEntity.setNormzlsqfm(editPlatformParam.getNormzlsqfm());
        int i = webPlatformDaoDao.updateByPrimaryKey(webPlatformEntity);
        if (i > 0) {
            return Res.ok("更新成功！");
        }
        return Res.error("更新失败！");
    }

    @Override
    public PageResult<WebPlatformViewModel> searchPlatforms(PlatformParam param) {

        PageHelper.startPage(param.getPage(), param.getPageSize());
        Mapper<WebPlatformEntity> myMapper = getMapper();
        Example example = new Example(WebPlatformEntity.class);
        example.setOrderByClause("createdate DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        if (param.getType() != null && param.getType() > 0) {
            criteria.andEqualTo("type", param.getType());
        }
        if (StringUtils.isNotBlank(param.getProvince())) {
            criteria.andEqualTo("province", param.getProvince());
        }
        if (StringUtils.isNotBlank(param.getCity())) {
            criteria.andEqualTo("city", param.getCity());
        }
        if (StringUtils.isNotBlank(param.getArea())) {
            criteria.andEqualTo("area", param.getArea());
        }
        if (StringUtils.isNotBlank(param.getName())) {
            criteria.andLike("name", "%" + param.getName().trim() + "%");
        }
        if (param.getRolesid() != null && param.getRolesid() > 0) {
            criteria.andEqualTo("rolesid", param.getRolesid());
        }
        if (param.getStatus() != null) {//平台状态
            criteria.andEqualTo("status", param.getStatus());
        }
        List<WebPlatformEntity> entities = myMapper.selectByExample(example);
        PageInfo<WebPlatformEntity> pageInfo = new PageInfo<WebPlatformEntity>(entities);
        if (entities != null && entities.size() > 0) {
            List<WebPlatformViewModel> models = new ArrayList<>();
            for (WebPlatformEntity entity : entities) {
                WebPlatformViewModel model = new WebPlatformViewModel();
                mapper.map(entity, model);
                if (entity.getRolesid() != null && entity.getRolesid() > 0) {
                    WebRolesEntity webRolesEntity = webRolesService.searchById(String.valueOf(entity.getRolesid()));
                    model.setRolesName(webRolesEntity.getName());
                }
                models.add(model);
            }
            return new PageResult<>(models, param.getPage(), param.getPageSize(), (int) pageInfo.getTotal());
        } else {
            return null;
        }
    }


    @Override
    public Integer saveOrUpdatePlatformWrap(PlatformViewParam param, int userId) {
        PlatformResult result = saveOrUpdatePlatform(param, userId);
        return result.getResult();
        // modify by wangze 2018-09-02
//        if (param.getId() != null && param.getId() > 0) {
//            return result.getResult();
//        } else {
//            Map<String, Object> map = new HashMap<>();
//            map.put("folder", result.getPlatform().getId());
//            map.put("param", result.getScheduleJob().getParams());
//            //初始化
//            HttpUtil.post(sysParamaterUtil.getInitOssDataUrl(), map); //初始化数据
//            Map<String, Object> postMap = new HashMap<>();
//            postMap.put("jobId", result.getScheduleJob().getId());
//            HttpUtil.post(sysParamaterUtil.getSaveQuartzJobUrl(), postMap);//保存定时更新任务
//            return result.getResult();
//        }


    }


    @Transactional
    public PlatformResult saveOrUpdatePlatform(PlatformViewParam param, int userId) {
        PlatformResult result = new PlatformResult();
        result.setResult(0);

        if (param.getId() != null && param.getId() > 0) {//编辑
            WebPlatformEntity entity = queryById(param.getId());
            mapper.map(param, entity);
            entity.setUpdatedate(new Date());
            entity.setUpdateoperid(userId);
            Integer successId = updateByNotNull(entity);

//            if (successId == 0) return 0;//更新失败
//            return 1;
            result.setResult(successId == 0 ? 0 : 1);
            return result;

        } else {//新增
            WebPlatformEntity entity = new WebPlatformEntity();
            mapper.map(param, entity);
            entity.setPatentcount(0);
            entity.setHomepageapplydate(1);
            entity.setNormzlsq(1);
            entity.setNormzlsqfm(1);
            entity.setSort(1);
            entity.setCreatedate(new Date());
            entity.setUpdatedate(new Date());
            entity.setStartdate(new Date());
            entity.setCreateoperid(userId);
            entity.setUpdateoperid(userId);
            Integer successId = saveByNotNull(entity);
            if (successId == 0) {
                return result;//新增失败
            }
            //更新平台区域表
            if (entity.getType() != null && entity.getType() == 1) {//省
                String province = entity.getProvince();
                if (province != null) {
                    List<String> citys = cfgAreaService.getCity(province);
                    if (citys != null && citys.size() > 0) {
                        Integer udSuccessId = updatePlatformarea(citys, entity, userId);
                        if (udSuccessId == 0) return result;//更新失败
                    }
                }
            }
            if (entity.getType() != null && entity.getType() == 2) {//市
                String city = entity.getCity();
                if (city != null) {
                    List<String> places = cfgAreaService.getPlace(city);
                    if (places != null && places.size() > 0) {
                        Integer udSuccessId = updatePlatformarea(places, entity, userId);
                        if (udSuccessId == 0) return result;//更新失败
                    }
                }
            }
            //添加数据稽核表
            String searchStrategy = "";
            if (entity.getType() != null && entity.getType() > 0) {
                searchStrategy = getSolrParam(entity);
            }
            AdminDataauditEntity adminDataauditEntity = new AdminDataauditEntity();
            adminDataauditEntity.setPlatformid(entity.getId());
            adminDataauditEntity.setStatus(1);
            adminDataauditEntity.setAudittype(1);//稽核方式为添加
            adminDataauditEntity.setSearchstrategy(searchStrategy);
            adminDataauditEntity.setCreatedate(new Date());
            adminDataauditEntity.setUpdatedate(new Date());
            adminDataauditEntity.setCreateoperid(userId);
            adminDataauditEntity.setUpdateoperid(userId);
            Integer dataauditSuccessId = adminDataauditService.saveDataaudit(adminDataauditEntity);
            if (dataauditSuccessId == 0) return result;//新增数据稽核表失败

            //添加数据更新表
            //ResourceBundle res = ResourceBundle.getBundle("/ScheduleJob");
//            ResourceBundle res = TemplateFileUtil.getBundle("ScheduleJob");
//            String beanName = res.getString("beanName");
//            String methodName = res.getString("methodName");


            // modify by wangze 暂时不做定时任务

//            ScheduleJobEntity scheduleJobEntity = new ScheduleJobEntity();
//            scheduleJobEntity.setDataid(adminDataauditEntity.getId());
//            scheduleJobEntity.setBeanname(sysParamaterUtil.getBeanName());
//            scheduleJobEntity.setMethodname(sysParamaterUtil.getMethodName());
//            scheduleJobEntity.setParams(searchStrategy);
//            scheduleJobEntity.setCronexpression("0 59 2 ? * FRI");
//            scheduleJobEntity.setStatus(0);
//            scheduleJobEntity.setCreatedate(new Date());
//            Integer sjsId = scheduleJobService.saveScheduleJob(scheduleJobEntity);
//            if (sjsId == 0) return result;//新增数据更新表失败

            result.setPlatform(entity);
            //result.setScheduleJob(scheduleJobEntity);
            result.setResult(1);
            return result;
        }
    }

    /**
     * 获取solr检索式
     *
     * @param entity
     * @return
     */
    private String getSolrParam(WebPlatformEntity entity) {
        switch (entity.getType()) {
            case 1://省
                String suffix = "省";
                if (Arrays.stream(UNIQUE_CITY).anyMatch(x -> x.equals(entity.getProvince()))) {
                    suffix = "市";
                }
                return "cdn:" + entity.getProvince() + suffix;
            case 2://市
                if (Arrays.stream(UNIQUE_CITY).anyMatch(x -> x.equals(entity.getProvince()))) {
                    return "cdn:" + entity.getCity() + "市";
                }
                return "cdn:" + entity.getProvince() + "省/" + entity.getCity() + "市";
            case 3://区县
            case 4://园区
                if (Arrays.stream(UNIQUE_CITY).anyMatch(x -> x.equals(entity.getProvince()))) {
                    return "cdn:" + entity.getCity() + "市/" + entity.getArea();
                }
                return "cdn:" + entity.getProvince() + "省/" + entity.getCity() + "市/" + entity.getArea();
            default:
                throw new RuntimeException("没有获取到平台类型");
        }

    }


    @Override
    @Transactional
    public Integer delPlatformById(String ids, int userId) {

        if (StringUtils.isNotBlank(ids)) {
            WebPlatformEntity entity = new WebPlatformEntity();
            entity.setStatus(-1);
            entity.setUpdatedate(new Date());
            entity.setUpdateoperid(userId);
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                entity.setId(Integer.parseInt(id));
                Integer successId = updateByNotNull(entity);
                if (successId == 0) return 0;//删除失败

                //删除数据稽核表
                int delDataId = adminDataauditDao.delDataauditByPlatformId(Integer.parseInt(id));
                if (delDataId == 0) return 0;//删除失败
                //删除定时任务,这里已经同步删除 scheduleJob数据了
                int scheduleJobId = scheduleJobDao.selectByPlatFormId(Integer.valueOf(id));
                HttpRequest.post(sysParamaterUtil.getDeleteQuartzJobUrl()).body(JSONUtil.toJsonStr(new long[]{scheduleJobId})).execute();
                //删除记录表
//                int scheduleId = scheduleJobDao.deleteById(scheduleJobId);
//                if (scheduleId == 0) return 0;//删除失败
            }
            return 1;
        }

        return 0;
    }

    @Override
    public Integer setStartDateById(int id, int userId) {

        if (id > 0) {

            WebPlatformEntity entity = queryById(id);
            entity.setStartdate(new Date());
            entity.setEnddate(null);
            entity.setUpdatedate(new Date());
            entity.setUpdateoperid(userId);
            Integer successId = update(entity);
            return successId;
        }
        return 0;//id传参有误，启用操作失败
    }

    @Override
    public Integer setDisabledById(int id, int userId) {
        if (id > 0) {
            //获得当前时间的前一天
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date bDate = calendar.getTime();
            WebPlatformEntity entity = new WebPlatformEntity();
            entity.setId(id);
            entity.setEnddate(bDate);
            entity.setUpdatedate(new Date());
            entity.setUpdateoperid(userId);
            Integer successId = updateByNotNull(entity);
            return successId;
        }
        return 0;//id传参有误，禁用操作失败
    }

    @Override
    public Integer setTryById(int id, int userId) {

        if (id > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.MONTH, 3);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date endDate = calendar.getTime();
            WebPlatformEntity entity = new WebPlatformEntity();
            entity.setId(id);
            entity.setStartdate(new Date());
            entity.setEnddate(endDate);
            entity.setUpdatedate(new Date());
            entity.setUpdateoperid(userId);
            Integer successId = updateByNotNull(entity);
            return successId;
        }
        return 0;//id传参有误，试用操作失败
    }

    @Override
    public WebPlatformEntity searchById(int id) {

        if (id > 0) {
            Mapper<WebPlatformEntity> mapperTk = getMapper();
            Example example = new Example(WebPlatformEntity.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andNotEqualTo("status", -1);
            criteria.andEqualTo("id", id);
            List<WebPlatformEntity> entities = mapperTk.selectByExample(example);
            if (entities == null || entities.size() == 0) return null;
//            WebPlatformEditModel model=new WebPlatformEditModel();
//            mapper.map(entity,model);
//            if(entity.getType()!=null&&entity.getType()>0){
//                switch (entity.getType()){
//                    case 1:
//                        model.setTypeStr("省");
//                    case 2:
//                        model.setTypeStr("市");
//                    case 3:
//                        model.setTypeStr("区县");
//                    case 4:
//                        model.setTypeStr("园区");
//                }
//            }
//            if(entity.getRolesid()!=null&&entity.getRolesid()>0){
//                WebRolesEntity rolesEntity=webRolesService.searchById(String.valueOf(entity.getRolesid()));
//                model.setRolesName(rolesEntity.getName());
//            }
            return entities.get(0);
        }

        return null;
    }

    @Override
    public List<WebPlatformEntity> searchPlatformsForUser() {
        Mapper<WebPlatformEntity> mapperTk = getMapper();
        Example example = new Example(WebPlatformEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        List<WebPlatformEntity> entities = mapperTk.selectByExample(example);
        if (entities != null && entities.size() > 0) return entities;
        return null;
    }

    @Override
    public List<WebPlatformEntity> searchByRolesId(int rolesId) {
        Mapper<WebPlatformEntity> mapperTk = getMapper();
        Example example = new Example(WebPlatformEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        criteria.andEqualTo("rolesid", rolesId);
        List<WebPlatformEntity> entities = mapperTk.selectByExample(example);
        if (entities != null && entities.size() > 0) return entities;
        return null;
    }

    @Override
    public Boolean chekPlatformName(String platformName) {
        Mapper mapperTk = getMapper();
        Example example = new Example(WebPlatformEntity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status", -1);
        criteria.andEqualTo("name", platformName);
        List<WebPlatformEntity> entities = mapperTk.selectByExample(example);
        if (entities != null && entities.size() > 0) return false;
        return true;
    }

    /**
     * code:420 AREA_UNINIT，指标未设置421 INDICATOR_UNINIT"
     *
     * @param platformid
     * @return
     */
    @Override
    public Res checkInit(Integer platformid) {
        //判断是否设置区域
        if (!web_platformareaService.checkHasAreaByPlatormId(platformid))
            return Res.error(420, "AREA_UNINIT");
        //是否都为0 返回false，如果是null自动生成为0 并返回false
        if (!cfgPatentIndicatorService.checkHasIndicatorByPlatormId(platformid)) {
            return Res.error(421, "INDICATOR_UNINIT");
        }
        return Res.ok();
    }

    private Integer updatePlatformarea(List<String> list, WebPlatformEntity entity, int userId) {
        for (String place : list) {
            WebPlatformareaEntity platformareaEntity = new WebPlatformareaEntity();
            platformareaEntity.setPlatformid(entity.getId());
            platformareaEntity.setName(place);
            platformareaEntity.setStatus(1);
            platformareaEntity.setSort(1);
            platformareaEntity.setCreatedate(new Date());
            platformareaEntity.setUpdatedate(new Date());
            platformareaEntity.setCreateoperid(userId);
            platformareaEntity.setUpdateoperid(userId);
            Integer paSuccessId = web_platformareaService.savePlatformarea(platformareaEntity);
            if (paSuccessId == 0) return 0;
        }

        return 1;
    }

    /**
     * 解析Excel表格内容
     *
     * @param is
     * @return
     */
    public List<String> analysisXls(InputStream is) {
        //InputStream is=file.getInputStream();
        //Map<Integer, String> content = new HashMap<Integer, String>();
        List<String> content = new ArrayList<>();
        String str = "";
        HSSFWorkbook wb = null;
        try {
            POIFSFileSystem fs = new POIFSFileSystem(is);
            wb = new HSSFWorkbook(fs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HSSFSheet sheet = wb.getSheetAt(0);
// 得到总行数
        int rowNum = sheet.getLastRowNum();
        HSSFRow row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            if (row == null) continue;
            int j = 0;
            while (j < colNum) {
                str += row.getCell((short) j);
                j++;
            }
            content.add(str);
            str = "";
        }
        return null;
    }
}
